package mspbots.smileback.data.core.reviews;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.smileback.common.ResultMsg;
import mspbots.smileback.data.core.AbstractToolsUtil;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * com.mspbots.core.amqp.receivers.TicketsReceiver
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2019/8/12
 */
@Log4j2
@Component
@RequiredArgsConstructor
public class ReviewsReceiver extends AbstractToolsUtil {

    private final ReviewsRepository reviewsRepository;

    @RabbitListener(queues = "smile-back.reviews.sync")
    public void processMsg(ResultMsg resultMsg) {

        Reviews data = Reviews.builder().otherId(resultMsg.getId()).build();
        data.setTenantId(resultMsg.getTenantId());
        data.setExtend(resultMsg.getEntity());
        data.setUpdateTime(LocalDateTime.parse(resultMsg.getEntity().get("last_modified").asText(),
                DateTimeFormatter.ISO_DATE_TIME));
        data.setCreateTime(LocalDateTime.now());
        data.setSyncTime(resultMsg.getSyncDate());

        this.reviewsRepository.findByOtherIdAndTenantId(data.getOtherId(), data.getTenantId())
                .map(result -> {
                    data.setId(result.getId());
                    return data;
                })
                .defaultIfEmpty(data)
                .flatMap(this.reviewsRepository::save).block(Duration.ofSeconds(10));

    }

}
